package com.kgcx.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.constant.Cons;
import com.kgcx.common.utils.ValidateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${kgcx.auth.timeout:30000}")
    private Long timeout;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String signature = request.getHeader("signature");
        log.debug("signature=" + signature);
        String timestamp = request.getHeader("timestamp");
        log.debug("timestamp=" + timestamp);
        if (StringUtils.isNotBlank(signature) && StringUtils.isNotBlank(timestamp)) {
            long now = System.currentTimeMillis();
            Date date = DateUtils.parseDate(timestamp, Cons.DATE_FORMAT_YYYYMMDDHHMMSSSSS);

            if (now - date.getTime() < timeout //时间戳对比当前时间超过30秒则不接受请求
                //&& now - date.getTime() > 0 //时间戳对比当前时间要早才接受请求
                    ) {
                if (ValidateUtils.validateSignature(timestamp, signature, request.getParameterMap())) {
                    return true;
                }
            }
        }
        log.error("鉴权失败！,url=" + request.getServletPath(), new Exception("鉴权失败！signature=" + signature + ".timestamp=" + timestamp));
        ReturnData returnData = new ReturnData("-1", "鉴权失败！");
        response.setContentType(ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8).toString());
        response.getWriter().print(JSON.toJSONString(returnData));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
